package com.gsj.web.shiro;

import com.gsj.domain.module.Module;
import com.gsj.domain.user.User;
import com.gsj.service.module.ModuleService;
import com.gsj.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 自定义的realm类，提供认证、授权数据访问的方法
 */
public class AuthRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken= (UsernamePasswordToken) token;
        String email = upToken.getUsername();
        User user = userService.findByEmail(email);
        if(user==null){
            return null;
        }
        String dbpassword = user.getPassword();
        //参数1：身份对象，找到的user对象
        //参数2：正确的密码
        //参数3：realm的名称；可以随便写。但是有多个realm要唯一，getName()获取默认名称
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user, dbpassword, getName());
        return sai;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //查询登录用户的权限
        //1.获取用户的身份对象
        User user = (User) principals.getPrimaryPrincipal();
        //2.根据用户的id查询权限
        List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
        //返回，告诉shiro当前登录用户拥有的权限，后面就可以进行权限校验
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        if(moduleList!=null&&moduleList.size()>0){
            for (Module module : moduleList) {
                //返回用户权限
                sai.addStringPermission(module.getName());
            }
        }
        return sai;
    }

}
